package org.jeecg.modules.monitoring.j_monitoring.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xkcoding.http.util.StringUtil;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.monitoring.j_monitoring.constantConfig.MonitorConstant;
import org.jeecg.modules.monitoring.j_monitoring.entity.MGlVirtualMachine;
import org.jeecg.modules.monitoring.j_monitoring.entity.MGlVirtualizationCluster;
import org.jeecg.modules.monitoring.j_monitoring.entity.VirtualClusterAddLog;
import org.jeecg.modules.monitoring.j_monitoring.mapper.MGlVirtualMachineMapper;
import org.jeecg.modules.monitoring.j_monitoring.mapper.MGlVirtualizationClusterMapper;
import org.jeecg.modules.monitoring.j_monitoring.mapper.VirtualClusterAddLogMapper;
import org.jeecg.modules.monitoring.j_monitoring.service.IMGlVirtualMachineService;
import org.jeecg.modules.monitoring.j_monitoring.service.IMGlVirtualizationClusterService;
import org.jeecgframework.core.util.ApplicationContextUtil;
import org.springframework.stereotype.Service;

import jakarta.annotation.Resource;
import java.util.*;

/**
 * @Description: 虚拟机(管理)
 * @Author: xiaoyq
 * @Date:   2023-02-22
 * @Version: V1.0
 */
@Service
public class MGlVirtualMachineServiceImpl extends ServiceImpl<MGlVirtualMachineMapper, MGlVirtualMachine> implements IMGlVirtualMachineService {
    @Resource
    private MGlVirtualizationClusterMapper clusterMapper;
    @Resource
    private VirtualClusterAddLogMapper logMapper;

    @Override
    public String getIp(String id) {
        return this.getById(id).getSystemIp();
    }




    @Override
    public JSONObject getDeviceMapById(JSONArray nodes, JSONArray edges, int startX, int startY,String id) {
        MGlVirtualMachine entity = this.getById(id);
        JSONObject result;
        JSONObject child = new JSONObject(),edge;
        child.put("category", MonitorConstant.VirtualMachine);
        child.put("id",entity.getId());
        child.put("ip",entity.getVirtualIp());
        child.put("name",entity.getName());
        child.put("x",startX + MonitorConstant.StepX * 1);
        child.put("y",startY);

        nodes.add(child);
        result = child;

        if(entity.getClusterId()!=null && !"".equals(entity.getClusterId())){
            IMGlVirtualizationClusterService clusterService = ApplicationContextUtil.getContext().getBean(IMGlVirtualizationClusterService.class);
            JSONObject root = clusterService.getDeviceMapById(nodes,edges,startX + MonitorConstant.StepX * 1,startY,entity.getClusterId());

            edge = new JSONObject();
            edge.put("source",entity.getId());
            edge.put("target",entity.getClusterId());
            edges.add(edge);
        }

        return result;
    }

    @Override
    public JSONObject getDeviceTreeById(String id) {
        MGlVirtualMachine entity = this.getById(id);
        JSONObject result;
        JSONObject child = new JSONObject();
        child.put("type","虚拟机");
        child.put("id",entity.getId());
        child.put("isCenter","1");
        child.put("ip",entity.getVirtualIp());
        child.put("name",entity.getName());
        result = child;

        if(entity.getClusterId()!=null && !"".equals(entity.getClusterId())){
            IMGlVirtualizationClusterService clusterService = ApplicationContextUtil.getContext().getBean(IMGlVirtualizationClusterService.class);
            JSONObject root = clusterService.getDeviceTreeById(entity.getClusterId());

            if(root!=null){
                JSONArray children = new JSONArray();
                children.add(root);
                result.put("children",children);
            }

        }

        return result;
    }

    @Override
    public int deleteAll(){
        return baseMapper.deleteAll();
    }


    public List<MGlVirtualMachine> dealImportList(List<MGlVirtualMachine> list , String ip) {
        List<MGlVirtualizationCluster> clusterList = clusterMapper.selectAll();

        for (MGlVirtualMachine machine : list){

            if (!machine.getCluster().contains("CR: ")){
                machine.setCluster("CR: "+ machine.getCluster());
            }
            //处理ip
            machine.setSystemIp(this.montageIp(ip,machine.getName()));
            //处理集群id
            machine.setClusterId(this.getClusterId(clusterList,machine.getCluster()));
        }
        return list;
    }

    public List<MGlVirtualMachine> selectAll() {
        return baseMapper.selectAll();
    }


    public String getClusterId(List<MGlVirtualizationCluster> clusterList , String name){
        for (MGlVirtualizationCluster cluster : clusterList){
            if (cluster.getName().equals(name)){
                return cluster.getId();
            }
        }
        return "";
    }

    public String montageIp(String ip,String name){

        if (StringUtil.isEmpty(name)){
            return "";
        }

        int leftBracketIndex = name.indexOf("[");
        int rightBracketIndex = name.indexOf("]");
        if (leftBracketIndex != -1 && rightBracketIndex != -1) {
            // 截取括号中间的内容
            String content = name.substring(leftBracketIndex + 1, rightBracketIndex);
            return ip + "." + content;
        }
        return "";
    }

    public void addNumberLog(){
        List<MGlVirtualMachine> newList = this.selectAll();

        Map<String,Integer> map = new HashMap<>();

        for (MGlVirtualMachine newData : newList){

            if (map.get(newData.getClusterId()) != null){
                int number = map.get(newData.getClusterId());
                number ++;
                map.put(newData.getClusterId(),number);
            }else{
                map.put(newData.getClusterId(),1);
            }

        }
        Map<String,Integer> mapCount = new HashMap<>();
        mapCount.putAll(map);

        List<VirtualClusterAddLog> lastList = logMapper.selectLastTimeData(DateUtils.getBeginMonth());

        for (VirtualClusterAddLog oldLog : lastList){

            if (map.get(oldLog.getClusterId()) != null){
                int number = map.get(oldLog.getClusterId());
                number -= oldLog.getCountNum();
                map.put(oldLog.getClusterId(),number);
            }

        }

        List<VirtualClusterAddLog> logList = new ArrayList<>();
        for(Map.Entry<String,Integer> entry : map.entrySet()){

            VirtualClusterAddLog log = new VirtualClusterAddLog();

            logMapper.deleteByRecordTimeAndClusterId(DateUtils.getBeginMonth(),entry.getKey());
            log.setId(UUID.randomUUID().toString().replace("-", ""));
            log.setAddNum(entry.getValue() > 0 ? entry.getValue() : 0);
            log.setClusterId(entry.getKey());
            log.setRecordTime(DateUtils.getBeginMonthDate());
            log.setCountNum(mapCount.get(entry.getKey()));
            logList.add(log);
        }

        if (logList.size()>0){
            logMapper.insertBatch(logList);
        }


    }
}
